/**
 * 开源协议 GPL
 * 版权所有 吉安码动未来信息科技有限公司
 * 微信联系 zyprosoft
*/
import axios from 'axios'
import {
	alertServerMsg
} from './common.js'
import {
	refreshToken,
	login
} from './api.js'
import {
	getToken,
	setToken,
	removeToken,
	commonLogin
} from './auth.js'
import config from './config.js'

const current = config.env;
const currentConfig = config[current];
const BASE_URL = currentConfig.base_url

// create an axios instance
const service = axios.create({
	baseURL: BASE_URL, // url = base url + request url
	// withCredentials: true, // send cookies when cross-domain requests
	timeout: 5000, // request timeout,
	method: 'POST'
})

axios.defaults.adapter = function(config) { //自己定义个适配器，用来适配uniapp的语法
	return new Promise((resolve, reject) => {
		console.log(config)
		var settle = require('axios/lib/core/settle');
		var buildURL = require('axios/lib/helpers/buildURL');
		uni.request({
			method: config.method.toUpperCase(),
			url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
			header: config.headers,
			data: config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete: function complete(response) {
				console.log("执行完成：", response)
				response = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config: config
				};

				settle(resolve, reject, response);
			}
		})
	})
}

// request interceptor
service.interceptors.request.use(
	config => {
		// do something before request is sent

		// if (store.getters.token) {
		//   // let each request carry token
		//   // ['X-Token'] is a custom headers key
		//   // please modify it according to the actual situation
		//   config.headers['X-Token'] = getToken()
		// }
		return config
	},
	error => {
		// do something with request error
		console.log(error) // for debug
		return Promise.reject(error)
	}
)

// response interceptor
service.interceptors.response.use(
	/**
	 * If you want to get http information such as headers or status
	 * Please return  response => response
	 */

	/**
	 * Determine the request status by custom code
	 * Here is just an example
	 * You can also judge the status by HTTP Status Code
	 */
	response => {
		const res = response.data
		console.log(JSON.stringify(res))

		// if the custom code is not 20000, it is judged as an error.
		if (res.code !== 0) {

			//登录凭证失效,主动让后台刷新一下session
			if (res.code == 30037 || res.code == 10012 || res.code == 10021) {
				removeToken()
				commonLogin()
				setTimeout(function() {
					uni.navigateTo({
						url: '/pages/login/login'
					})
				}, 200);
			}
			//token刷新非法，并且与数据库不一致，需要重新登陆
			if (res.code == 10023 || res.code == 30017) {
				if (getToken() !== null && getToken() !== undefined) {
					//删掉Token重新登陆
					removeToken()
				}
				uni.navigateTo({
					url: '/pages/login/login'
				})
			}
			//token过期，需要重新刷新
			if (res.code == 10022) {
				refreshToken().then(res => {
					//刷新成功，保存下来
					setToken(res.data)
				}).catch(error => {
					//token刷新不成功，删掉Token去登陆
					removeToken()
					uni.navigateTo({
						url: '/pages/login/login'
					})
				})
			}

			//翻译错误信息
			let transMsg = res.message
			switch (res.code) {
				case 10014:
					transMsg = '验证码填写错误'
					break;
				case 10015:
					transMsg = '验证码创建失败'
					break;
				case 10013:
					transMsg = '验证码已过期'
					break;
				case 10012:
					transMsg = '请先登陆再操作!'
					break;
				case 10008:
					transMsg = '此操作要求管理员身份'
					break;
				case 10001:
					transMsg = '令牌非法'
					break;
				case 10004:
					transMsg = '鉴权失败'
					break;
				case 9994:
					transMsg = '访问频率过快'
					break;
				case 10021:
					transMsg = '请先登陆后再操作'
					break;
				case 10022:
					transMsg = 'token已经过期请重新登陆'
					break;
				case 10023:
					transMsg = 'token已经过期并且不正确'
					break
				case 30037:
					transMsg = '会话已过期，如遇登录失败，请多尝试几次!'
					break
				default:
					break;
			}

			console.log(transMsg)
			uni.$emit('ShowNetworkMsg', transMsg)

			let error = new Error(res.message || 'Error')
			error.data = res.data
			error.code = res.code
			return Promise.reject(error)
		} else {
			return res
		}
	},
	error => {
		console.log('err' + error) // for debug
		uni.showToast({
			icon: 'none',
			title: '(' + error.code + ')' + error.message,
			duration: 2500
		})
		return Promise.reject(error)
	}
)

export default service
